//
//  OANewEmailViewController.m
//  LongOA
//
//  Created by XuJiuming on 15/9/16.
//  Copyright (c) 2015年 梁文朗. All rights reserved.
//

#import "OANewEmailViewController.h"
#import "NIDropDown.h"
#import "OAAccount.h"
#import "GetContactsRequest.h"
#import "GetContactsResponse.h"
#import "PlaceholderTextView.h"
#import "SendMailRequest.h"
#import "SendMailResponse.h"
#import "MessagePhotoView.h"
#import "MessagePhotoMenuItem.h"
#import "OASelectFileViewController.h"
#import "OATempMail.h"

@interface OANewEmailViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDataSource, UITableViewDelegate,THContactPickerDelegate,NIDropDownDelegate,MessagePhotoViewDelegate,MessagePhotoItemDelegate,UIScrollViewDelegate,ZYQAssetPickerControllerDelegate,UIAlertViewDelegate>
{
    UITextField* txtAccount;
    UITextField* txtTitle;
    NIDropDown *dropDownColumn;
    UIView *_maskV;
    PlaceholderTextView *_txtView;
    //UIImagePickerController *pickerTake;
}
@property (nonatomic) UIImagePickerController *imagePickerController;
@property(nonatomic,strong) NSMutableArray *itemArray;
@property(nonatomic,strong) NSMutableArray *imageArray;
@property(nonatomic,strong) UIScrollView *photoScrollView;
@property (nonatomic,strong) NSMutableArray* imgArr;
@property (nonatomic,strong) MessagePhotoView *photoView;
@property (nonatomic, strong) NSMutableArray *privateSelectedContacts;
@property (nonatomic, strong) NSArray *filteredContacts;
@end

@implementation OANewEmailViewController
//static const CGFloat kPickerViewHeight = 100.0;

NSString *THContactPickerContactCellReuseID = @"THContactPickerContactCell";

@synthesize contactPickerView = _contactPickerView;
@synthesize strReply;
@synthesize openTempMail;

- (void)leftBarClicked:(id)sender {
    if (_txtView.text.length>0 || (txtTitle.text.length>0 && self.privateSelectedContacts.count>0)) {
        UIAlertView* alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否保存到草稿箱" delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"保存", nil];
        [alert show];
    } else {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}
-(NSString*)GetCurrentTimeString1 {
    NSDateFormatter *dateformat = [[NSDateFormatter  alloc]init];
    [dateformat setDateFormat:@"yyyy-MM-dd HH:mm"]; //:ss
    return [dateformat stringFromDate:[NSDate date]];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex==1) {
        OATempMail* tempMail=[[OATempMail alloc] init];
        tempMail.msgid=[self GetCurrentTimeString];
        NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
        tempMail.token=token;
        if (txtTitle.text.length>0) {
            tempMail.title=txtTitle.text;
        }
        tempMail.content=_txtView.text;
        NSString* strRec=nil;
        for (int i=0; i<self.privateSelectedContacts.count; i++) {
            if (i==0) {
                strRec=[self.privateSelectedContacts objectAtIndex:i];
            } else {
                strRec=[NSString stringWithFormat:@"%@;%@",strRec,[self.privateSelectedContacts objectAtIndex:i]];
            }
        }
        tempMail.receiver=strRec;
        tempMail.savetime1=[self GetCurrentTimeString1];
        
        if (_imageArray.count>0) {
            tempMail.atttag=@"1";
            NSString* strRec=nil;
            for (int i=0; i<_imageArray.count; i++) {
                if (i==0) {
                    strRec=[self.privateSelectedContacts objectAtIndex:i];
                } else {
                    strRec=[NSString stringWithFormat:@"%@;%@",strRec,[self.privateSelectedContacts objectAtIndex:i]];
                }
            }
            tempMail.attPath=strRec;
        } else {
            tempMail.atttag=@"0";
            tempMail.attPath=@"";
        }

        [tempMail saveToDB];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDraft" object:@"Draft"];
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (void)rightBarClicked:(id)sender {
    if (self.privateSelectedContacts.count==0) {
        [self showAlertWithContent:@"请选择接收人"];
    }
    if (txtTitle.text.length==0) {
        [self showAlertWithContent:@"请输入标题"];
    }
    if (_txtView.text.length==0) {
        [self showAlertWithContent:@"请输入内容"];
    }
    NSString* strRec=nil;
    for (int i=0; i<self.privateSelectedContacts.count; i++) {
        if (i==0) {
            strRec=[self.privateSelectedContacts objectAtIndex:i];
        } else {
            strRec=[NSString stringWithFormat:@"%@;%@",strRec,[self.privateSelectedContacts objectAtIndex:i]];
        }
    }
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    
    SendMailRequest* request = [[SendMailRequest alloc] init];
    request.token = token;
    request.title=txtTitle.text;
    request.content=_txtView.text;
    request.receiver=strRec;
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[SendMailResponse class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    SendMailResponse* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
        [self showAlertWithContent:rslt.ErrMsg];
    }
    else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSend" object:nil];
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}];
}
- (UILabel *)createLabel:(NSString *)title withR:(CGRect)rect {
    UILabel *lab1=[[UILabel alloc]initWithFrame:rect];
    lab1.backgroundColor=[UIColor clearColor];
    lab1.text=title;
    lab1.textAlignment=NSTextAlignmentRight;
    lab1.font=[UIFont systemFontOfSize:14.0];
    lab1.textColor=[UIColor darkTextColor];
    
    return lab1;
}
-(void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createNavWithTitle:@"写邮件" createMenuItem:^UIView *(int nIndex)
     {
         float btnwidth=40.0f;
         float btnheight=40.0f;
         if (nIndex ==0)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(10.0f, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             [btn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(leftBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
             return btn;
         }
         
         if (nIndex ==2)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(self.navView.width - btnwidth, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             UIImage *img=[self resizeImage:[UIImage imageNamed:@"ic_send"] withWidth:24.0 withHeight:24.0];
             [btn setImage:img forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(rightBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             
             return btn;
         }
         
         return nil;
     }];
    _imageArray=[[NSMutableArray alloc] init];
    
    float fwidth=60.0;
    UILabel* lab1=[self createLabel:@"账号:" withR:CGRectMake(0.0, self.navView.frame.size.height, fwidth, 30.0)];
    [self.view addSubview:lab1];
    UIView* vi=[[UIView alloc] initWithFrame:CGRectMake(3.0, lab1.frame.origin.y+lab1.frame.size.height, SCREEN_WIDTH-6.0, 0.5)];
    vi.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [self.view addSubview:vi];
    UITextField* txt1=[[UITextField alloc] initWithFrame:CGRectMake(lab1.right, lab1.frame.origin.y, SCREEN_WIDTH-lab1.right-30.0, 30.0)];
    txt1.text=[[NSUserDefaults standardUserDefaults] objectForKey:@"accname"];
    txt1.font=[UIFont systemFontOfSize:14.0];
    txt1.textAlignment=NSTextAlignmentCenter;
    txt1.textColor=[UIColor darkTextColor];
    txt1.userInteractionEnabled=NO;
    txt1.tag=1010;
    [self.view addSubview:txt1];
    UIButton* btnArrow=[[UIButton alloc] initWithFrame:CGRectMake(txt1.right, lab1.frame.origin.y+4.5, 21.0, 21.0)];
    [btnArrow setBackgroundImage:[UIImage imageNamed:@"ic_down_normal"] forState:UIControlStateNormal];
    [btnArrow addTarget:self action:@selector(showAccount:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnArrow];
    
    UILabel* lab2=[self createLabel:@"接收人:" withR:CGRectMake(0.0, lab1.frame.origin.y+lab1.frame.size.height+2.0, fwidth, 40.0)];
    [self.view addSubview:lab2];
    UIView* vi1=[[UIView alloc] initWithFrame:CGRectMake(3.0, lab2.frame.origin.y+lab2.frame.size.height, SCREEN_WIDTH-6.0, 0.5)];
    vi1.backgroundColor=[UIColor groupTableViewBackgroundColor];
    vi1.tag=301;
    [self.view addSubview:vi1];
    // Initialize and add Contact Picker View
    self.contactPickerView = [[THContactPickerView alloc] initWithFrame:CGRectMake(lab2.right, vi.bottom
                                                                                   , SCREEN_WIDTH-lab2.right-33.0, 25.0)];
    self.contactPickerView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
    self.contactPickerView.delegate = self;
    [self.contactPickerView setPlaceholderLabelText:@""]; //Who would you like to message?
    [self.contactPickerView setPromptLabelText:@""];  //To:
    //[self.contactPickerView setLimitToOne:YES];
    //self.contactPickerView.userInteractionEnabled=NO;
    [self.view addSubview:self.contactPickerView];
    
//    CALayer *layer = [self.contactPickerView layer];
//    [layer setShadowColor:[[UIColor colorWithRed:225.0/255.0 green:226.0/255.0 blue:228.0/255.0 alpha:1] CGColor]];
//    [layer setShadowOffset:CGSizeMake(0, 2)];
//    [layer setShadowOpacity:1];
//    [layer setShadowRadius:1.0f];
    //+4.5
    UIButton* btnArrow1=[[UIButton alloc] initWithFrame:CGRectMake(txt1.right-8, lab2.frame.origin.y, 30.0, 30.0)];
//    [btnArrow1 setBackgroundImage:[UIImage imageNamed:@"btn_add"] forState:UIControlStateNormal];
//    [btnArrow1 setBackgroundImage:[UIImage imageNamed:@"btn_add_pressed"] forState:UIControlStateHighlighted];
    [btnArrow1 setImage:[UIImage imageNamed:@"btn_add"] forState:UIControlStateNormal];
    [btnArrow1 setImage:[UIImage imageNamed:@"btn_add_pressed"] forState:UIControlStateHighlighted];
    [btnArrow1 addTarget:self action:@selector(showContact:) forControlEvents:UIControlEventTouchUpInside];
    btnArrow1.tag=2020;
    [self.view addSubview:btnArrow1];
    
    
    UILabel* lab3=[self createLabel:@"标题:" withR:CGRectMake(0.0, lab2.frame.origin.y+lab2.frame.size.height+2.0, fwidth, 30.0)];
    lab3.tag=302;
    [self.view addSubview:lab3];
    UIView* vi2=[[UIView alloc] initWithFrame:CGRectMake(3.0, lab3.frame.origin.y+lab3.frame.size.height, SCREEN_WIDTH-6.0, 0.5)];
    vi2.backgroundColor=[UIColor groupTableViewBackgroundColor];
    vi2.tag=303;
    [self.view addSubview:vi2];
    txtTitle=[[UITextField alloc] initWithFrame:CGRectMake(lab3.right+5.0, lab3.frame.origin.y, SCREEN_WIDTH-lab3.right-20.0, 30.0)];
    txtTitle.font=[UIFont systemFontOfSize:14.0];
    txtTitle.textColor=[UIColor darkTextColor];
    [self.view addSubview:txtTitle];
    if (strReply.length>0) {
        [self.privateSelectedContacts addObject:strReply];
        [self.contactPickerView addContact:strReply withName:strReply];
        txtTitle.text=[NSString stringWithFormat:@"回复:%@",strReply];
    }
    
    float fmargin=15.0f;
    _txtView=[[PlaceholderTextView alloc] initWithFrame:CGRectMake(fmargin, vi2.bottom, SCREEN_WIDTH-fmargin*2.0, 120.0f)];
    _txtView.placeholder=@"内容";
    _txtView.font=[UIFont boldSystemFontOfSize:15];
    _txtView.placeholderFont=[UIFont boldSystemFontOfSize:14];
    //    _txtView.layer.borderWidth=0.5;
    //    _txtView.layer.borderColor=[UIColor lightGrayColor].CGColor;
    _txtView.placeholderColor=[UIColor lightGrayColor];
    _txtView.textColor=[UIColor darkTextColor];
    _txtView.backgroundColor=[UIColor clearColor];
    _txtView.tag=304;
    [self.view addSubview:_txtView];
    
    [_txtView addMaxTextLengthWithMaxLength:5 andEvent:^(PlaceholderTextView *text) {
        
        //NSLog(@"----------");
    }];
    
    [_txtView addTextViewBeginEvent:^(PlaceholderTextView *text) {
        //NSLog(@"begin");
    }];
    
    [_txtView addTextViewEndEvent:^(PlaceholderTextView *text) {
        //NSLog(@"end");
    }];
//    self.contacts = [NSArray arrayWithObjects:@"",@"", nil];

    //阴影
    _maskV = [[UIView alloc] initWithFrame:CGRectMake(0, self.navView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - self.navView.bottom)];
    [_maskV setClipsToBounds:YES];
    [self.view addSubview:_maskV];
    [_maskV setHidden:YES];
    UIView *bg = [[UIView alloc] initWithFrame:_maskV.bounds];
    [bg setBackgroundColor:[UIColor blackColor]];
    [bg setAlpha:0.5];
    [_maskV addSubview:bg];
    UITapGestureRecognizer *tSM = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMenuByTap:)];
    [bg addGestureRecognizer:tSM];
    
    // Fill the rest of the view with the table view
    CGRect tableFrame = CGRectMake(SCREEN_WIDTH-110.0, 0, 110, SCREEN_HEIGHT - self.navView.bottom);
    self.tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self setExtraCellLineHidden:_tableView];
    //[self.view insertSubview:self.tableView belowSubview:self.contactPickerView];
    [_maskV addSubview:self.tableView];
    
    
    [self getContactList];
    
    float fvHeight=26.0f;
    float fvWidth=30.0f;
    UIView *view8=[[UIView alloc] initWithFrame:CGRectMake(-1.0, SCREEN_HEIGHT-44.0, SCREEN_WIDTH+2.0, 44)];
    view8.layer.borderColor=[UIColor darkTextColor].CGColor;
    view8.layer.borderWidth=1.0f;
    view8.tag=8080;
    [self.view addSubview:view8];
    
    float fspace=(SCREEN_WIDTH-50.0*2-fvWidth*3)/2.0;
    UIButton *customButton1 = [[UIButton alloc] initWithFrame:CGRectMake(50.0, (44.0-fvHeight)/2.0, fvWidth, fvHeight)];
    [customButton1 addTarget:self action:@selector(leftBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [customButton1 setImage:[UIImage imageNamed:@"icon_attach_toolbar_camera"] forState:UIControlStateNormal];
    [customButton1 setImage:[UIImage imageNamed:@"icon_attach_toolbar_camera_pressed"] forState:UIControlStateHighlighted];
    [view8 addSubview:customButton1];
    UIButton *customButton2 = [[UIButton alloc] initWithFrame:CGRectMake(customButton1.right+fspace, (44.0-fvHeight)/2.0, fvWidth, fvHeight)];
    [customButton2 addTarget:self action:@selector(middleBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [customButton2 setImage:[UIImage imageNamed:@"icon_attach_toolbar_album"] forState:UIControlStateNormal];
    [customButton2 setImage:[UIImage imageNamed:@"icon_attach_toolbar_album_pressed"] forState:UIControlStateHighlighted];
    [view8 addSubview:customButton2];
    UIButton *customButton3 = [[UIButton alloc] initWithFrame:CGRectMake(customButton2.right+fspace, (44.0-fvHeight)/2.0, fvWidth, fvHeight)];
    [customButton3 addTarget:self action:@selector(rightBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [customButton3 setImage:[UIImage imageNamed:@"icon_attach_toolbar_file"] forState:UIControlStateNormal];
    [customButton3 setImage:[UIImage imageNamed:@"icon_attach_toolbar_file_pressed"] forState:UIControlStateHighlighted];
    [view8 addSubview:customButton3];
    
//    self.photoView = [[MessagePhotoView alloc]initWithFrame:CGRectMake(5.0, SCREEN_HEIGHT-60.0,SCREEN_WIDTH-5.0*2, 60.0f)];
//    [self.view addSubview:self.photoView];
//    self.photoView.backgroundColor=[UIColor whiteColor];
//    self.photoView.layer.borderColor=[UIColor lightGrayColor].CGColor;
//    self.photoView.layer.borderWidth=0.6;
//    self.photoView.layer.cornerRadius=5.0;
//    self.photoView.delegate = self;
//    self.photoView.hidden=YES;
    _photoScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0, SCREEN_HEIGHT-80.0,SCREEN_WIDTH, 80.0f)];
    _photoScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-view8.bottom);
    _photoScrollView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    _photoScrollView.showsVerticalScrollIndicator=NO;
    _photoScrollView.showsHorizontalScrollIndicator=NO;
    _photoScrollView.hidden=YES;
    [self.view addSubview:_photoScrollView];
    _itemArray = [[NSMutableArray alloc]init];

    //open temp mail
    if (openTempMail) {
        txtTitle.text=openTempMail.title;
        _txtView.text=openTempMail.content;
        [self.privateSelectedContacts addObject:openTempMail.receiver];
        [self.contactPickerView addContact:openTempMail.receiver withName:openTempMail.receiver];
        
        NSString* strPath=openTempMail.attPath;
        if (strPath.length>0) {
            NSArray* arr=[strPath componentsSeparatedByString:@";"];
            for (int i=0; i<arr.count; i++) {
                NSString* onePath=[arr objectAtIndex:i];
                [_imageArray addObject:onePath];
                UIImage *image=nil;
                if ([[onePath pathExtension] isEqualToString:@"jpg"] || [[onePath pathExtension] isEqualToString:@"png"] || [[onePath pathExtension] isEqualToString:@"bmp"] || [[onePath pathExtension] isEqualToString:@"JPG"] || [[onePath pathExtension] isEqualToString:@"PNG"] || [[onePath pathExtension] isEqualToString:@"BMP"]) {
                    image=[[UIImage alloc] initWithContentsOfFile:onePath];
                } else {
                    image=[UIImage imageNamed:@"filetype_word_h32"];
                }
                [self addImage:image withUrl:onePath withType:@"picture"];
                if (_photoScrollView.hidden) {
                    UIView* vi1=(UIView*)[self.view viewWithTag:8080];
                    CGRect frame = vi1.frame;
                    frame.origin.y = SCREEN_HEIGHT-44.0-80.0;
                    vi1.frame = frame;
                    _photoScrollView.hidden=NO;
                }
            }
        }
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPicFromPath:) name:@"ADDPATHPIC" object:nil];
}
- (void)addPicFromPath:(NSNotification*)notificaiton {
    NSString* onePath=notificaiton.object;
    UIImage *image=nil;
    if ([[onePath pathExtension] isEqualToString:@"jpg"] || [[onePath pathExtension] isEqualToString:@"png"] || [[onePath pathExtension] isEqualToString:@"bmp"] || [[onePath pathExtension] isEqualToString:@"JPG"] || [[onePath pathExtension] isEqualToString:@"PNG"] || [[onePath pathExtension] isEqualToString:@"BMP"]) {
        image=[[UIImage alloc] initWithContentsOfFile:onePath];
    } else {
        image=[UIImage imageNamed:@"filetype_word_h32"];
    }
    [self addImage:image withUrl:onePath withType:@"picture"];
    if (_photoScrollView.hidden) {
        UIView* vi1=(UIView*)[self.view viewWithTag:8080];
        CGRect frame = vi1.frame;
        frame.origin.y = SCREEN_HEIGHT-44.0-80.0;
        vi1.frame = frame;
        _photoScrollView.hidden=NO;
    }

}
#pragma mark Bottom ToolBar
- (void)leftBtnPressed:(id)sender {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        //
        if (!self.imagePickerController) {
            UIImagePickerController *pickerTake = [[UIImagePickerController alloc]init];
            pickerTake.delegate = self;
            //设置拍照后的图片可被编辑
            pickerTake.allowsEditing = YES;
            pickerTake.sourceType = sourceType;
            self.imagePickerController = pickerTake;
        }
        //[self presentViewController:pickerTake animated:YES completion:nil];
        
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
        
    }else{
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)middleBtnPressed:(id)sender {
    //导航栏颜色保持和当前一致
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName]];
    [self localPhoto];
}
- (void)rightBtnPressed:(id)sender {
    OASelectFileViewController* vc=[[OASelectFileViewController alloc] init];
    //[self.navigationController pushViewController:vc animated:NO];
    [self presentViewController:vc animated:NO completion:nil];
}
-(NSString*)GetCurrentTimeString {
    NSDateFormatter *dateformat = [[NSDateFormatter  alloc]init];
    [dateformat setDateFormat:@"yyyyMMddHHmmss"];
    return [dateformat stringFromDate:[NSDate date]];
}
#pragma mark MessagePhotoView
//实现代理方法
-(void)addPicker:(UIImagePickerController *)picker{
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)selectItemArray:(NSMutableArray *)array {
    for (int i=0; i<[array count]; i++) {
        ALAsset *asset=array[i];
        CGImageRef ref = [[asset defaultRepresentation]fullScreenImage];
        //CGImageRef ref = [[asset defaultRepresentation]fullResolutionImage];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref];
        
        NSString* strTime=[self GetCurrentTimeString];
        NSString* strfile=[NSString stringWithFormat:@"%@.jpg",strTime];
        NSString* strfile1=[kImagesFolder stringByAppendingPathComponent:strfile];
        [UIImageJPEGRepresentation(img, 0.5) writeToFile:strfile1 atomically:YES];
        
        [_imgArr addObject:strTime];
    }
}
- (void)takePhoto:(UIImage *)image {
    NSString* strTime=[self GetCurrentTimeString];
    NSString* strfile=[NSString stringWithFormat:@"%@.jpg",strTime];
    NSString* strfile1=[kImagesFolder stringByAppendingPathComponent:strfile];
    [UIImageJPEGRepresentation(image, 0.5) writeToFile:strfile1 atomically:YES];
    
    [_imgArr addObject:strTime];
}
-(void)addUIImagePicker:(UIImagePickerController *)picker {
    //    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
    //        self.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    //    }
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)deleteImage:(NSInteger)index {
    [_imgArr removeObjectAtIndex:index];
}

- (void)showContact:(id)sender {
    UIButton *btn = (UIButton *)sender;
    [btn setUserInteractionEnabled:NO];
    [btn setSelected:!btn.selected];
    [self showMenuWithBool:btn.selected complete:^()
     {
         [btn setUserInteractionEnabled:YES];
     }];
}
- (void)showMenuWithBool:(BOOL)bShow complete:(void(^)())complete
{
    if (bShow)
    {
        [_maskV setHidden:NO];
        [UIView animateWithDuration:0.3 animations:^
         {
             //_menuV.top = 0;
         } completion:^(BOOL finished)
         {
             complete();
         }];
    }else
    {
        [UIView animateWithDuration:0.3 animations:^
         {
             //_menuV.top = -_menuV.height;
         } completion:^(BOOL finished)
         {
             [_maskV setHidden:YES];
             complete();
         }];
    }
}

- (void)showMenuByTap:(UITapGestureRecognizer *)tap
{
    UIButton *btn = (UIButton *)[self.view viewWithTag:2020];
    [btn setUserInteractionEnabled:NO];
    [btn setSelected:!btn.selected];
    [self showMenuWithBool:btn.selected complete:^()
     {
         [btn setUserInteractionEnabled:YES];
     }];
}
- (void)getContactList {
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    
    GetContactsRequest* request = [[GetContactsRequest alloc] init];
    request.token = token;
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[GetContactsResponse class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    GetContactsResponse* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
    }
    else{
        NSMutableArray* arr=[[NSMutableArray alloc] init];
        for (int i=0; i<rslt.list.count; i++) {
            NSDictionary* dict=[rslt.list objectAtIndex:i];
            [arr addObject:[dict objectForKey:@"username"]];
        }
        
        self.contacts=arr;

        [_tableView reloadData];
    }
}];
}
- (void)showAccount:(id)sender {
    NSArray *arr = [[NSArray alloc] init];
    NSArray* allAccounts = [OAAccount searchWithWhere:nil];
    NSMutableArray* arrTemp=[[NSMutableArray alloc] init];
    for (OAAccount* account in allAccounts)
    {
        [arrTemp addObject:account.name];
    }
    if (arrTemp.count>0) {
        arr=arrTemp;
    }
    NSArray * arrImage = [[NSArray alloc] init];
    arrImage = nil;
    if ([arr count]==0) {
        return;
    }
    //    if (dropDownColumn) {
    //        [dropDownColumn hideDropDown:sender];
    //        dropDownColumn=nil;
    //    }
    if(dropDownColumn == nil) {
        CGFloat f = 33*([arr count]+1);
        if (f>33*5) {
            f=33.0*5.0;
        }
        UITextField* txt1=(UITextField*)[self.view viewWithTag:1010];
        CGFloat width=txt1.width;
        CGFloat xx=txt1.frame.origin.x;
        CGFloat yy=txt1.bottom;
        
        dropDownColumn=[[NIDropDown alloc] showDropDown:sender withHeight:&f withContent:arr withImg:nil withDirect:@"down" withWidth:&width withX:&xx withY:&yy withView:self.view];
        dropDownColumn.delegate = self;
        dropDownColumn.tag=6;
    }
    else {
        [dropDownColumn hideDropDown:sender];
        dropDownColumn=nil;
    }
}
#pragma mark 下拉菜单 dropdown delegate
- (void)feedBackInfo:(NIDropDown *)sender withRow:(int)irow withCotent:(NSString *)strcontent {
    UITextField* txtName=(UITextField*)[self.view viewWithTag:1010];
    txtName.text=strcontent;
    dropDownColumn=nil;
}
- (void) niDropDownDelegateMethod: (NIDropDown *) sender {
}
-(UIImage*)resizeImage:(UIImage*)image withWidth:(CGFloat)width withHeight:(CGFloat)height
{    CGSize newSize = CGSizeMake(width, height);
    CGFloat widthRatio = newSize.width/image.size.width;
    CGFloat heightRatio = newSize.height/image.size.height;
    
  
  if(widthRatio > heightRatio)
    {
        newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
    }
    else
    {
        newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
    }
    
    
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSArray *)selectedContacts{
    return [self.privateSelectedContacts copy];
}

#pragma mark - Publick properties

- (NSArray *)filteredContacts {
    if (!_filteredContacts) {
        _filteredContacts = _contacts;
    }
    return _filteredContacts;
}

- (void)adjustTableViewInsetTop:(CGFloat)topInset bottom:(CGFloat)bottomInset {
    self.tableView.contentInset = UIEdgeInsetsMake(topInset,
                                                   self.tableView.contentInset.left,
                                                   bottomInset,
                                                   self.tableView.contentInset.right);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
}

- (NSInteger)selectedCount {
    return self.privateSelectedContacts.count;
}

#pragma mark - Private properties

- (NSMutableArray *)privateSelectedContacts {
    if (!_privateSelectedContacts) {
        _privateSelectedContacts = [NSMutableArray array];
    }
    return _privateSelectedContacts;
}

#pragma mark - Private methods

- (void)adjustTableFrame {
    CGFloat yOffset = self.contactPickerView.frame.origin.y + self.contactPickerView.frame.size.height;
    
    CGRect tableFrame = CGRectMake(0, yOffset, self.view.frame.size.width, self.view.frame.size.height - yOffset);
    self.tableView.frame = tableFrame;
}

- (void)adjustTableViewInsetTop:(CGFloat)topInset {
    [self adjustTableViewInsetTop:topInset bottom:self.tableView.contentInset.bottom];
}

- (void)adjustTableViewInsetBottom:(CGFloat)bottomInset {
    [self adjustTableViewInsetTop:self.tableView.contentInset.top bottom:bottomInset];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.font=[UIFont systemFontOfSize:14.0];
    cell.textLabel.text = [self titleForRowAtIndexPath:indexPath];
}

- (NSPredicate *)newFilteringPredicateWithText:(NSString *) text {
    return [NSPredicate predicateWithFormat:@"self contains[cd] %@", text];
}

- (NSString *)titleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.filteredContacts objectAtIndex:indexPath.row];
}

- (void) didChangeSelectedItems {
    
}

#pragma mark - UITableView Delegate and Datasource functions
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //8.0的分割线额外设置
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
            [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.filteredContacts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:THContactPickerContactCellReuseID];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:THContactPickerContactCellReuseID];
    }
    
    [self configureCell:cell atIndexPath:indexPath];
    
    if ([self.privateSelectedContacts containsObject:[self.filteredContacts objectAtIndex:indexPath.row]]){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    id contact = [self.filteredContacts objectAtIndex:indexPath.row];
    NSString *contactTilte = [self titleForRowAtIndexPath:indexPath];
    
    if ([self.privateSelectedContacts containsObject:contact]){ // contact is already selected so remove it from ContactPickerView
        cell.accessoryType = UITableViewCellAccessoryNone;
        [self.privateSelectedContacts removeObject:contact];
        [self.contactPickerView removeContact:contact];
    } else {
        // Contact has not been selected, add it to THContactPickerView
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.privateSelectedContacts addObject:contact];
        [self.contactPickerView addContact:contact withName:contactTilte];
        //
        //		UIColor *color = [UIColor blueColor];
        //		if (self.privateSelectedContacts.count % 2 == 0){
        //			color = [UIColor orangeColor];
        //		} else if (self.privateSelectedContacts.count % 3 == 0){
        //			color = [UIColor purpleColor];
        //		}
        //		THContactViewStyle *style = [[THContactViewStyle alloc] initWithTextColor:[UIColor whiteColor] backgroundColor:color cornerRadiusFactor:2.0];
        //		THContactViewStyle *selectedStyle = [[THContactViewStyle alloc] initWithTextColor:[UIColor whiteColor] backgroundColor:[UIColor greenColor] cornerRadiusFactor:2.0];
        //		[self.contactPickerView addContact:contact withName:contactTilte withStyle:style andSelectedStyle:selectedStyle];
    }
    
    self.filteredContacts = self.contacts;
    [self didChangeSelectedItems];
    [self.tableView reloadData];
}

#pragma mark - THContactPickerTextViewDelegate

- (void)contactPickerTextViewDidChange:(NSString *)textViewText {
    if ([textViewText isEqualToString:@""]){
        self.filteredContacts = self.contacts;
    } else {
        NSPredicate *predicate = [self newFilteringPredicateWithText:textViewText];
        self.filteredContacts = [self.contacts filteredArrayUsingPredicate:predicate];
    }
    [self.tableView reloadData];
}

- (void)contactPickerDidResize:(THContactPickerView *)contactPickerView {
    UIView* vi1=(UIView*)[self.view viewWithTag:301];
    CGRect frame = vi1.frame;
    frame.origin.y = contactPickerView.frame.size.height + contactPickerView.frame.origin.y;
    vi1.frame = frame;
    
    UILabel* lab1=(UILabel*)[self.view viewWithTag:302];
    frame = lab1.frame;
    frame.origin.y = vi1.bottom;
    lab1.frame=frame;
    
    frame=txtTitle.frame;
    frame.origin.y=vi1.bottom;
    txtTitle.frame=frame;
    
    UIView* vi2=(UIView*)[self.view viewWithTag:303];
    frame = vi2.frame;
    frame.origin.y = lab1.bottom;
    vi2.frame = frame;
    
    frame=_txtView.frame;
    frame.origin.y=vi2.bottom;
    _txtView.frame=frame;
}

- (void)contactPickerDidRemoveContact:(id)contact {
    [self.privateSelectedContacts removeObject:contact];
    
    NSInteger index = [self.contacts indexOfObject:contact];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    cell.accessoryType = UITableViewCellAccessoryNone;
    [self didChangeSelectedItems];
}

- (BOOL)contactPickerTextFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length > 0){
        NSString *contact = [[NSString alloc] initWithString:textField.text];
        [self.privateSelectedContacts addObject:contact];
        [self.contactPickerView addContact:contact withName:textField.text];
    }
    return YES;
}

#pragma  mark - NSNotificationCenter

- (void)keyboardDidShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect kbRect = [self.view convertRect:[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:self.view.window];
    [self adjustTableViewInsetBottom:self.tableView.frame.origin.y + self.tableView.frame.size.height - kbRect.origin.y];
}

- (void)keyboardDidHide:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect kbRect = [self.view convertRect:[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:self.view.window];
    [self adjustTableViewInsetBottom:self.tableView.frame.origin.y + self.tableView.frame.size.height - kbRect.origin.y];
}

/*
 新加的另外的方法
 */
////////////////////////////////////////////////////////////
//打开相册，可以多选
-(void)localPhoto{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc]init];
    //    picker.navigationBar.barTintColor = [UIColor colorWithRed:0.0f/255.0f green:203.0f/255.0f blue:98.0f/255.0f alpha:1.0f];
    //    picker.navigationBar.tintColor = [UIColor whiteColor];
    picker.maximumNumberOfSelection = 9;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings){
        if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
            return duration >= 10;
        }else{
            return  YES;
        }
    }];
    
    //[self.delegate addPicker:picker];
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma  mark   -ZYQAssetPickerController Delegate
/*
 得到选中的图片
 */
#pragma mark - ZYQAssetPickerController Delegate
//跳转到大图显示页面
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    //[self.scrollview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    //NSLog(@"self.itemArray is %lu",(unsigned long)self.photoMenuItems.count);
    
    //跳转到显示大图的页面
    //ShowBigViewController *big = [[ShowBigViewController alloc]init];
    
    //big.arrayOK = [NSMutableArray arrayWithArray:assets];
    //追加状态
    for (int i=0; i<assets.count; i++) {
        ALAsset *asset=assets[i];
        UIImage *image=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        
        NSString *saveUrl=[self saveImage:image withType:@"picture"];
        [self addImage:image withUrl:saveUrl withType:@"picture"];
        [_imageArray addObject:saveUrl];
        
        if (_photoScrollView.hidden) {
            UIView* vi1=(UIView*)[self.view viewWithTag:8080];
            CGRect frame = vi1.frame;
            frame.origin.y = SCREEN_HEIGHT-44.0-80.0;
            vi1.frame = frame;
            _photoScrollView.hidden=NO;
            //NSLog(@"assets is %lu",(unsigned long)assets.count);
        }

    }
    
    //    if (self.photoMenuItems.count>0) {
    //        [self.photoMenuItems addObjectsFromArray:[NSMutableArray arrayWithArray:assets]];
    //    } else
    //        self.photoMenuItems = [NSMutableArray arrayWithArray:assets];
    
    
    //NSLog(@"%lu",(unsigned long)self.photoMenuItems.count);
    //[self initlizerScrollView:self.photoMenuItems];
    //NSLog(@"arraryOk is %d",big.arrayOK.count);
    //[picker pushViewController:big animated:YES];
    [self selectItemArray:[NSMutableArray arrayWithArray:assets]];
    
}
/////////////////////////////////////////////////////////
-(NSString *)saveImage1:(UIImage *)image withType:(NSString *)type withPath:(NSString*)strPath
{
    image=[self scaleImage:image toScale:0.3];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.29);
    
    NSString *fileName = nil;//[[formatter stringFromDate:date] stringByAppendingPathExtension:@"jpg"];
    
    NSString *temp=[NSString stringWithFormat:@"%@%@",strPath,@"mi"];
    fileName=[temp stringByAppendingPathExtension:@"jpg"];
    
    
    //NSString *filePath=[sandBox stringByAppendingPathComponent:fileName];
    [imageData writeToFile:fileName atomically:YES];
    
    return fileName; //[sandBox stringByAppendingPathComponent:fileName];
}
- (UIImage *)scaleImage:(UIImage *)image1 toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image1.size.width * scaleSize, image1.size.height * scaleSize));
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width * scaleSize, image1.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
}
//将照片保存到disk上
-(NSString *)saveImage:(UIImage *)image withType:(NSString *)type
{
    //    NSData *imageData = UIImagePNGRepresentation(image);
    //    if(imageData == nil)
    //    {
    //        imageData = UIImageJPEGRepresentation(image, 1.0);
    //    }
    image=[self scaleImage:image toScale:0.3];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.29);
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *fileName = nil;//[[formatter stringFromDate:date] stringByAppendingPathExtension:@"jpg"];
  
    fileName = [[formatter stringFromDate:date] stringByAppendingPathExtension:@"jpg"];
    
    //    NSURL *saveURL = [NSURL URLWithString:[sandBox stringByAppendingPathComponent:fileName]];
    //    [imageData writeToURL:saveURL atomically:YES];
    NSString *filePath=[kImagesFolder stringByAppendingPathComponent:fileName];
    [imageData writeToFile:filePath atomically:YES];
    
    return [kImagesFolder stringByAppendingPathComponent:fileName];
}
//选择某张照片之后
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if([type isEqualToString:@"public.image"]){
        //获取照片实例
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSString *saveUrl=[self saveImage:image withType:@"picture"];
        [self addImage:image withUrl:saveUrl withType:@"picture"];
        [_imageArray addObject:saveUrl];
        
        if (_photoScrollView.hidden) {
            UIView* vi1=(UIView*)[self.view viewWithTag:8080];
            CGRect frame = vi1.frame;
            frame.origin.y = SCREEN_HEIGHT-44.0-80.0;
            vi1.frame = frame;
            _photoScrollView.hidden=NO;
        }
        
        //保存到相册
        //        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        //        [library writeImageToSavedPhotosAlbum:[image CGImage]
        //                            orientation:(ALAssetOrientation)[image imageOrientation]
        //                            completionBlock:nil];
        
        //       NSData *datas=UIImageJPEGRepresentation(image, 0.5);
        //        UIImage *image1 = [UIImage imageWithData:datas];
        //[self reloadDataWithImage:image];
        
        //[self.delegate takePhoto:image];
        /*
         NSData *datas;
         if(UIImagePNGRepresentation(image)==nil){
         datas = UIImageJPEGRepresentation(image, 1.0);
         }else{
         datas = UIImagePNGRepresentation(image);
         }
         
         //图片保存的路径
         //这里将图片放在沙盒的documents文件夹中
         NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
         //文件管理器
         NSFileManager *fileManager = [NSFileManager defaultManager];
         //把刚才图片转换的data对象拷贝至沙盒中,并保存为image.png
         [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
         [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:datas attributes:nil];
         //得到选择后沙盒中图片的完整路径
         filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,@"/image.png"];
         
         //创建一个选择后图片的图片放在scrollview中
         
         //加载scrollview中
         */
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //NSLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//添加图像到列表
- (void)addImage:(UIImage *)image withUrl:(NSString *)saveUrl withType:(NSString *)dataType {
    //int i=0;
    int j=0;
    float fmargin=15.0f;
    float fspace=10.0f;
    float ItemWidth = (SCREEN_WIDTH - fmargin*2 - fspace*2)/3;
    //float ItemHeight = 50.0f;
    int iColumn=0;
    int iRow=0;
    
    j=(int)[self.itemArray count]; //+1;
//    iColumn = j%3;
//    iRow = j/3;
    iColumn=j;
    iRow=0;
    
    MessagePhotoMenuItem *photoItem = [[MessagePhotoMenuItem alloc]initWithFrame:CGRectMake(fmargin+iColumn * (ItemWidth+fspace), iRow*(ItemWidth-10.0+7.0), ItemWidth, ItemWidth-10.0) withType:dataType];
    photoItem.delegate = self;
    photoItem.index = j;
    photoItem.contentImage = image;
    photoItem.filePath=saveUrl;
    photoItem.dataType=dataType;
    
    [self.photoScrollView addSubview:photoItem];
    [self.itemArray addObject:photoItem];
    
    //[self.photoScrollView setContentSize:CGSizeMake(SCREEN_WIDTH,(iRow+1)*ItemWidth)];
    [self.photoScrollView setContentSize:CGSizeMake((ItemWidth+10.0)*(j+1)+20.0,80)];
}
- (void)updateScrollView:(NSMutableArray *)itemList {
    [self.photoScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    float fmargin=15.0f;
    float fspace=10.0f;
    float ItemWidth = (SCREEN_WIDTH - fmargin*2 - fspace*2)/3;
    //float ItemHeight = 50.0f;
    int iColumn=0;
    int iRow=0;
    for (int j=0; j<[itemList count]; j++) {
        iColumn = j; //j%3;
        iRow = 0; //j/3;
        MessagePhotoMenuItem *photoItem = [self.itemArray objectAtIndex:j];
        photoItem.frame=CGRectMake(fmargin+iColumn * (ItemWidth+fspace), iRow*(ItemWidth-10.0+7.0), ItemWidth, ItemWidth-10.0);
        photoItem.index = j;
        photoItem.contentImage=[UIImage imageWithContentsOfFile:photoItem.filePath];
        //NSLog(@"%@---%@",photoItem.filePath,photoItem.dataType);
        [self.photoScrollView addSubview:photoItem];
        //[self.itemArray addObject:photoItem];
        [self.photoScrollView setContentSize:CGSizeMake((ItemWidth+10.0)*(j+1)+20.0,80)];
    }
}
#pragma mark - MessagePhotoItemDelegate
- (void)messagePItemView:(MessagePhotoMenuItem *)messagePItem withTouch:(NSInteger)index withImgView:(UIImageView *)imgView{
//    if ([messagePItem.dataType isEqualToString:@"picture"]) {
//        [self localImageShow:index withImgView:imgView];
//    } else if ([messagePItem.dataType isEqualToString:@"video"]) {
//        NSString *_mp4Path=messagePItem.filePath;
//        _mp4Path= [_mp4Path stringByReplacingOccurrencesOfString:@"jpg" withString:@"mp4"];
//        MPMoviePlayerViewController* playerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://localhost/private%@", _mp4Path]]];
//        //NSLog(@"%@",[NSString stringWithFormat:@"file://localhost/private%@", _mp4Path]);
//        playerView.moviePlayer.shouldAutoplay=NO;
//        [self presentViewController:playerView animated:YES completion:nil];
//        //[playerView.moviePlayer stop];
//    } else {
//        //music
//        NSString *strMusic=[NSString stringWithFormat:@"%@.wav",[messagePItem.filePath stringByDeletingPathExtension]];
//        strMusic=[strMusic stringByReplacingOccurrencesOfString:@"mi" withString:@""];
//        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
//        [[AVAudioSession sharedInstance] setActive:YES error:nil];
//        self.player = [self.player initWithContentsOfURL:[NSURL URLWithString:strMusic] error:nil];
//        [self.player play];
//    }
}
-(void)messagePhotoItemView:(MessagePhotoMenuItem *)messagePhotoItemView didSelectDeleteButtonAtIndex:(NSInteger)index{
    //从目录删除
    //打开拍照前，或者上传完毕删除所有文件
//    if ([messagePhotoItemView.dataType isEqualToString:@"video"]) {
//        NSFileManager *fm = [NSFileManager defaultManager];
//        NSArray *fileList = [[fm contentsOfDirectoryAtPath:sandBox error:nil] pathsMatchingExtensions:[NSArray arrayWithObjects:@"mp4",nil]];
//        for (int i=0 ; i<[fileList count]; i++) {
//            NSError *error;
//            NSString *filepath = [sandBox stringByAppendingPathComponent:[fileList objectAtIndex:i]];
//            [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
//        }
//        NSError *error;
//        NSString *filepath = [self.imageArray objectAtIndex:index];
//        [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
//    } else if ([messagePhotoItemView.dataType isEqualToString:@"picture"]) {
//        NSError *error;
//        NSString *filepath = [self.imageArray objectAtIndex:index];
//        [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
//    } else {
//        //music
//        NSFileManager *fm = [NSFileManager defaultManager];
//        NSArray *fileList = [[fm contentsOfDirectoryAtPath:sandBox error:nil] pathsMatchingExtensions:[NSArray arrayWithObjects:@"wav",@"amr",nil]];
//        for (int i=0 ; i<[fileList count]; i++) {
//            NSError *error;
//            NSString *filepath = [sandBox stringByAppendingPathComponent:[fileList objectAtIndex:i]];
//            [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
//        }
//        NSError *error;
//        NSString *filepath = [self.imageArray objectAtIndex:index];
//        [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
//    }
//    [self.itemArray removeObjectAtIndex:index];
//    [self.imageArray removeObjectAtIndex:index];
//    [self updateScrollView:self.itemArray];
    
}

@end
